package sword.chapter7Queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 滑动窗口的平均值
 *
 * 队列 先进先出
 *
 * @author K
 * @date 2021-12-05 16:47
 */
public class S41MovingAverage {
    public static void main(String[] args) {
        MovingAverage movingAverage = new MovingAverage(3);
        double next = movingAverage.next(1);
        double next2 = movingAverage.next(2);
        double next3 = movingAverage.next(3);
        double next4 = movingAverage.next(3);
        System.out.println();
    }
}

class MovingAverage {
    private Queue<Integer> nums;
    private int capacity;
    private int sum;
    public MovingAverage(int size) {
        this.capacity = size;
        nums = new LinkedList<>();
    }

    public double next(int val) {
        if (nums.size() < capacity) {
            nums.add(val);
            sum+=val;
            return (double) sum/nums.size();
        }
        sum -= nums.poll();
        sum += val;
        nums.add(val);
        return (double)sum/3;
    }

}